<template>
  <el-card shadow="never">
      <!-- 搜索栏 -->
      <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="queryParams.deptName" placeholder="请输入部门名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="部门状态" clearable>
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
        </el-col>
      </el-row>

      <!-- 树形表格 -->
      <el-table
        v-if="refreshTable"
        v-loading="loading"
        element-loading-text="加载中..."
        :data="deptList"
        row-key="deptId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="deptName" label="部门名称" width="260" />
        <el-table-column prop="orderNum" label="排序" width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="200">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)">新增</el-button>
            <el-button v-if="scope.row.parentId != 0" link type="primary" icon="Delete" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改部门对话框 -->
    <el-dialog v-model="open" :title="title" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <el-tree-select
                v-model="form.parentId"
                :data="deptOptions"
                :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="选择上级部门"
                check-strictly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, getCurrentInstance } from 'vue';
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from '@/api/system/dept';
import { ElMessage, ElMessageBox } from 'element-plus';

defineOptions({
  name: 'Dept',
});

const { proxy } = getCurrentInstance() as any;

const loading = ref(true);
const showSearch = ref(true);
const deptList = ref<any[]>([]);
const deptOptions = ref<any[]>([]);
const title = ref('');
const open = ref(false);
const isExpandAll = ref(true);
const refreshTable = ref(true);

const queryParams = ref<any>({
  deptName: undefined,
  status: undefined,
});

const form = ref<any>({});

const rules = reactive({
  parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
  deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
});

const queryFormRef = ref();
const formRef = ref();

function getList() {
  loading.value = true;
  listDept(queryParams.value)
    .then((response: any) => {
      deptList.value = proxy.handleTree(response.data, 'deptId');
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}

function getTreeselect() {
  deptOptions.value = [];
  listDept().then((response: any) => {
    const dept = { deptId: 0, deptName: '主类目', children: [] };
    dept.children = proxy.handleTree(response.data, 'deptId');
    deptOptions.value.push(dept);
  });
}

function cancel() {
  open.value = false;
  reset();
}

function reset() {
  form.value = {
    deptId: undefined,
    parentId: undefined,
    deptName: undefined,
    orderNum: 0,
    leader: undefined,
    phone: undefined,
    email: undefined,
    status: '0',
  };
  formRef.value?.resetFields();
}

function handleQuery() {
  getList();
}

function resetQuery() {
  queryFormRef.value?.resetFields();
  handleQuery();
}

function handleAdd(row?: any) {
  reset();
  getTreeselect();
  if (row != undefined && row.deptId) {
    form.value.parentId = row.deptId;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = '添加部门';
}

function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  setTimeout(() => {
    refreshTable.value = true;
  }, 0);
}

function handleUpdate(row: any) {
  reset();
  getDept(row.deptId).then((response: any) => {
    form.value = response.data;
    open.value = true;
    title.value = '修改部门';
    getTreeselect();
  });
}

function submitForm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.deptId != undefined) {
        updateDept(form.value).then(() => {
          ElMessage.success('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addDept(form.value).then(() => {
          ElMessage.success('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleDelete(row: any) {
  ElMessageBox.confirm('是否确认删除名称为"' + row.deptName + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(function () {
      return delDept(row.deptId);
    })
    .then(() => {
      getList();
      ElMessage.success('删除成功');
    });
}

getList();
</script>

<style scoped lang="scss">
@use '@/styles/common.scss';

// 优化搜索表单间距
.el-form {
  margin-bottom: 8px;
  
  .el-form-item {
    margin-bottom: 12px;
  }
}

// 优化按钮组间距
.el-row.mb8 {
  margin-bottom: 8px;
}

// 彻底清除 Element Plus 默认样式
:deep(.el-row) {
  margin-left: 0 !important;
  margin-right: 0 !important;
  margin: 0 !important;
  
  .el-col {
    padding-right: 0 !important;
  }
}

// 覆盖所有可能的 Element Plus 默认 gutter 样式
:deep(.el-row[style*="margin-left"]) {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

// 优化对话框表单间距
:deep(.el-dialog) {
  .el-form {
    .el-form-item {
      margin-bottom: 22px; // 增加底部间距以容纳错误信息
      
      // 当有错误信息时，调整间距
      &.is-error {
        margin-bottom: 24px;
        
        .el-form-item__error {
          margin-top: 2px;
          font-size: 12px;
          line-height: 1.2;
          padding: 0;
        }
      }
      
      // 当没有错误信息时，保持紧凑间距
      &:not(.is-error) {
        margin-bottom: 18px;
      }
    }
    
    .el-row {
      margin-bottom: 0;
      
      .el-col {
        padding-left: 8px;
        padding-right: 8px;
        
        &:first-child {
          padding-left: 0;
        }
        
        &:last-child {
          padding-right: 0;
        }
      }
    }
  }
  
  .el-dialog__body {
    padding: 20px 20px 0 20px;
  }
  
  .el-dialog__footer {
    padding: 10px 20px 20px 20px;
    text-align: right;
    
    .el-button + .el-button {
      margin-left: 8px;
    }
  }
}
</style>
